﻿/*
创建人：longb
日期：2022-03-21
描述：装试工艺工时维护js
*/
var page = {
    commonUrl: getRootPath() + "/Ashx/CommonHandler.ashx", //通用方法后台路径
    mainUrl: getRootPath() + "/Ashx/ZsHandler/ZSProcessHandler.ashx", //本页面后台路径
    //初始化页面
    init: function () {
        page.bind();
        page.initData(); //初始化页面数据
    },
    //页面事件绑定
    bind: function () {
        //列表加载
        $("#gdStepInfo").datagrid({
            checkOnSelect: false,
            selectOnCheck: false,
            singleSelect: true,
            columns: [[
                { field: 'ck', title: '选择', checkbox: true },
		        { field: 'SPECNO', title: '工序号', width: 100 },
		        { field: 'OPDESC', title: '工序内容', width: 100 },
            //{ field: 'PARENTSPECNO', title: '父工序号', width: 100 },
                {field: 'SPECTYPENAME', title: '工序类型', width: 100 },
                { field: 'FACTORYCODE', title: '分厂', width: 100 },
                { field: 'ISLASTSTEP', title: '是否末序', width: 80 },
                { field: 'ISKEY', title: '是否关键工序', width: 80 },
                { field: 'ISBOTTLENECK', title: '是否瓶颈工序', width: 80 },
                { field: 'PARALLELGROUPNAME', title: '并行工序组', width: 80 },
            //{ field: 'ITEMPROCESS', title: '子工艺', width: 100 },
            //    {field: 'TEAMNAME', title: '责任组', width: 100 },
                 { field: 'PREPARECYCLE', title: '准备时间', width: 100 },
                 { field: 'MAKECYCLE', title: '加工时间', width: 100 },
                 { field: 'TRANSFERCYCLE', title: '运转时间', width: 100 },
                 { field: 'CHANGEOVERCYCLE', title: '换型时间', width: 100 },
                { field: 'WORKSTATIONIDS', title: '工位ID', width: 100, hidden: true },
                { field: 'WORKSTATIONNAME', title: '工位', width: 100 },
                ]],
                onSelect:function(rowIndex,rowData){
                    var rows= $("#gdStepInfo").datagrid("getSelected");
                    
                    $('#PREPARECYCLE').numberbox('setValue',rows.PREPARECYCLE);
                    $('#MAKECYCLE').numberbox('setValue',rows.MAKECYCLE) ;
                    $('#TRANSFERCYCLE').numberbox('setValue',rows.TRANSFERCYCLE);
                    $('#CHANGEOVERCYCLE').numberbox('setValue',rows.CHANGEOVERCYCLE);
                    $('#IsBottLeneck').combobox('setValue',rows.ISBOTTLENECK==null?0:rows.ISBOTTLENECK);
                    var data=[];
                    $.each(rows.WORKSTATIONIDS.split(','),function(index,item){
                        data.push({WORKSTATIONID:item,WORKSTATIONNAME:rows.WORKSTATIONNAME.split(',')[index]});
                    });
                    page.InitWorkStation(data);
                    $('#WorkStationID').combobox('setValues',rows.WORKSTATIONIDS.split(','));
                },
                onUnselect:function(rows){
                    $('#setForm').form('clear');
                }
        });
        //绑定件号选择组件
        $("#productContent").productCombo({
            search: function () {
                clearEasyuiDataGrid("gdStepInfo");
                $("#workflowContent").workflowCombo("init"); //同时恢复初始化工艺下拉组件
            },
            cancel: function () { //件号取消点击事件
                clearEasyuiDataGrid("gdStepInfo");
                $("#workflowContent").workflowCombo("init"); //同时恢复初始化工艺下拉组件
                $('#workflowCopy').combobox('clear');
                $('#workflowCopy').combobox('loadData',[]);
            },
            selected: function (val, text) {//件号下拉选择事件
                clearEasyuiDataGrid("gdStepInfo");
                $("#workflowContent").workflowCombo("init"); //同时恢复初始化工艺下拉组件
                $("#workflowContent").workflowCombo("setCombo", { productName: text }); //联动工艺下拉
                page.InitWorkFlowCopyCom(text);
            }
        });
        //绑定工艺选择组件
        $("#workflowContent").workflowCombo({
            //            param: { isThisFactory: true },
            cancel: function () {//工艺取消点击事件
                clearEasyuiDataGrid("gdStepInfo");
                $('#workflowCopy').combobox('clear');
                $('#workflowCopy').combobox('loadData',[]);
            },
            selected: function (val, text) {//工艺下拉选择事件
                clearEasyuiDataGrid("gdStepInfo");
                page.search(val);
            }
        });
        //查询
        $("#btnSearch").on("click", function () {
            var workflowId = $("#workflowContent").workflowCombo("getValue");
            if (isNullOrWhiteSpaceStr(workflowId)) {
                displayMessage("没有选择工艺路线", false);
                return;
            }
            page.search(workflowId);
        }),
        //属性获取
        $('#btnOtherRev').on("click", function () {
            clearMessage();
            page.copyOtherRev();
        });
        //保存
        $('#btnSave').on("click", function () {
            clearMessage();
            page.save();
        });
        $(function () {
        page.InitUploader();
        });
    },
    initData: function () {

        page.post({ action: "GetWorkcenterByFactory" }, function (res) {
            $('#WorkcenterID').combobox({
                data: res,
                valueField: 'WORKCENTERID',
                textField: 'WORKCENTERNAME',
                onSelect: function (record) {
                    page.GetTeamByWorkcenter(record.WORKCENTERID);
                }
            });
        });
    },
    GetTeamByWorkcenter: function (WorkcenterID) {
        page.post({ action: "GetShiftByWorkcenter", workcenterId: WorkcenterID }, function (res) {
            $('#ShiftID').combobox({
                data: res,
                valueField: 'SHIFTID',
                textField: 'SHIFTNAME',
                onSelect: function (record) {
                    page.GetWorkStationByTeam(record.SHIFTID);
                }
            });
        });
    },
    GetWorkStationByTeam: function (ShiftID) {
        page.post({ action: "GetWorkStationByShift", ShiftID: ShiftID }, function (res) {
            page.InitWorkStation(res);
        });
    },
    InitWorkStation:function(data){
        $('#WorkStationID').combobox({
                data: data,
                valueField: 'WORKSTATIONID',
                textField: 'WORKSTATIONNAME',
                onSelect: function (row) {
                    var opts = $(this).combobox('options');
                    var el = opts.finder.getEl(this, row[opts.valueField]);
                    el.find('input.combobox-checkbox')._propAttr('checked', true);
                },
                onUnselect: function (row) {
                    var opts = $(this).combobox('options');
                    var el = opts.finder.getEl(this, row[opts.valueField]);
                    el.find('input.combobox-checkbox')._propAttr('checked', false);
                },
                 formatter: function (row) {
                    var opts = $(this).combobox('options');
                    return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
                },
            });
    },
    InitParallelGroup: function (data) {
        $('#ParallelGroup').combobox({
            data: data,
            valueField: 'PARALLELGROUPNAME',
            textField: 'PARALLELGROUPNAME'
        });
    },
    //查询
    search: function (workflowId) {
        clearEasyuiDataGrid("gdStepInfo");
        var formData = {
            action: "GetStepData",
            workflowId: workflowId
        };
        $.postAjax({
            url: page.mainUrl,
            data: formData,
            ajaxSuccess: function (res) {
                if (res.Result) {
                    $("#gdStepInfo").datagrid('loadData', { rows: res.DBTable });
                    page.InitParallelGroup(res.ReturnData);
                } else {
                    displayMessage(res.Message, res.Result);
                }
            }
        });
    },
    //设置责任班组
    SetTeam: function () {
        var shiftID = $('#ShiftID').combobox('getValue');
        var shiftName = $('#ShiftID').combobox('getText');
        var rows = $("#gdStepInfo").datagrid('getChecked');
        if (rows.length == 0) { displayMessage('请勾选至少一条工序信息，再进行操作', false); return; }
        var WorkStationNAME = $('#WorkStationID').combobox('getText');
        var WorkStationID = $('#WorkStationID').combobox('getValues').join(',');
         if (WorkStationID == "") { displayMessage('请先选择工位，再进行操作', false); return; }
        var PREPARECYCLE = $('#PREPARECYCLE').numberbox('getValue')==''?0:$('#PREPARECYCLE').numberbox('getValue');
        var MAKECYCLE = $('#MAKECYCLE').numberbox('getValue') ;
        var TRANSFERCYCLE = $('#TRANSFERCYCLE').numberbox('getValue')==''?0:$('#TRANSFERCYCLE').numberbox('getValue');
        var CHANGEOVERCYCLE = $('#CHANGEOVERCYCLE').numberbox('getValue');
        var IsBottLeneck = $('#IsBottLeneck').combobox('getText');
        if(CHANGEOVERCYCLE==0){CHANGEOVERCYCLE=parseInt(PREPARECYCLE)+parseInt(TRANSFERCYCLE);}
        $.each(rows, function (index, item) {
            var inddexx = $("#gdStepInfo").datagrid('getRowIndex', item);
            $("#gdStepInfo").datagrid('updateRow', { index: inddexx, row: { SHIFTID: shiftID, SHIFTNAME: shiftName, WORKSTATIONIDS: WorkStationID, WORKSTATIONNAME: WorkStationNAME,ISBOTTLENECK:IsBottLeneck, PREPARECYCLE: PREPARECYCLE, MAKECYCLE: MAKECYCLE, TRANSFERCYCLE: TRANSFERCYCLE,CHANGEOVERCYCLE:CHANGEOVERCYCLE} })
        });
    },
    //设置装配周期
    SetAssemblyCycle: function () {
        var AssemblyCycle = $('#AssemblyCycle').textbox('getValue');
        var rows = $("#gdStepInfo").datagrid('getChecked');
        if (rows.length == 0) { displayMessage('请勾选至少一条工序信息，再进行操作', false); return; }
        if (AssemblyCycle == "") { displayMessage('请输入装配周期，再进行操作', false); return; }
        $.each(rows, function (index, item) {
            var inddexx = $("#gdStepInfo").datagrid('getRowIndex', item);
            $("#gdStepInfo").datagrid('updateRow', { index: inddexx, row: { ASSEMBLYCYCLE: AssemblyCycle} })
        });
    },
    //设定并行工序组
    SetParallelGroup: function () {
        var ParallelGroup = $('#ParallelGroup').textbox('getValue');
        var rows = $("#gdStepInfo").datagrid('getChecked');
        if (rows.length == 0) { displayMessage('请勾选至少一条工序信息，再进行操作', false); return; }
        //if (ParallelGroup == "") { displayMessage('请输入或选择并行工序组名称，再进行操作', false); return; }
        var arr = [];
        $.each(rows, function (index, item) {
            if (item.PARALLELGROUPNAME != "" && item.PARALLELGROUPNAME != null) {
                arr.push(item.PARALLELGROUPNAME);
            }
        })
        var Allrows = $("#gdStepInfo").datagrid('getRows');
        var maxArr = [];
        $.each(Allrows, function (index, item) {
            if (item.PARALLELGROUPNAME != "" && item.PARALLELGROUPNAME != null) {
                maxArr.push(item.PARALLELGROUPNAME);
            }
        })
        var minNum = 1;
        if (arr.length > 0) {
            minNum = Math.min.apply(null, arr);
        }
        if (maxArr.length > 0 && arr.length == 0) {
            minNum = Math.max.apply(null, maxArr) + 1;
        }
        $.each(rows, function (index, item) {
            var inddexx = $("#gdStepInfo").datagrid('getRowIndex', item);
            $("#gdStepInfo").datagrid('updateRow', { index: inddexx, row: { PARALLELGROUPNAME: minNum} })
        });
    },
    SaveProcessMaintain: function () {
        var rows = $("#gdStepInfo").datagrid('getRows');
        var param = {
            action: "SaveProcessMaintain",
            data: JSON.stringify(rows)
        };
        page.post(param, function (res) {
            if (res.Result) {
                var workflowId = $("#workflowContent").workflowCombo("getValue");
                page.search(workflowId);
                $('#setForm').form('clear');
            }
            displayMessage(res.Message, res.Result);
        });
    },

    //导入组件初始化
    InitUploader: function () {
        var uploader = WebUploader.create({
            // swf文件路径
            swf: page.rootPath + "/Content/webuploader/Uploader.swf",
            // 文件接收服务端。
            server: page.mainUrl,
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#btnLMApsImport',
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            formData: {
                    action: "ImportWorkFlowStepTime",
                },
            accept: {
                    title: 'Excel',
                    extensions: 'xlsx,xls',
                    mimeTypes: 'excel/*'
                },
        });
        // 当有文件被添加进队列的时候，每次只传一个文件
        uploader.on('fileQueued', function (file) {
            if ($('#txtExcelFileId').val() != "") {
                var f = uploader.getFile($('#txtExcelFileId').val()); //找到上一次队列中的文件
                uploader.removeFile(f, true); //删除掉上一次队列中的文件
            }
            $('#txtExcelFileId').val(file.id);
            displayMessage("", true);
            uploader.upload();
            $.messager.progress({ text: '', msg: '处理中...' });
        });
        //上传成功
        uploader.on('uploadSuccess', function (file, response) {
            displayMessage("", true);
            var result = response;
            displayMessage(result.Message, false);
            $.messager.progress('close');
            if(result.ReturnData!=null){if(result.ReturnData.length>0){page.loadErrorData(result.ReturnData);}}
            var f = uploader.getFile(file.id); //找到上传的文件
            uploader.removeFile(f, true); //将其从队列中的删掉
            $('#txtExcelFileId').val("");

        });
        //上传失败
        uploader.on('uploadError', function (file) {
            displayMessage("上传失败", false);
            var f = uploader.getFile(file.id); //找到上传的文件
            uploader.removeFile(f, true); //将其从队列中的删掉
            $.messager.progress('close');
            $('#txtExcelFileId').val("");

        });
    },
    loadErrorData:function(data)
    {
        $('#ErrorDg').dialog({
                title: '导入错误数据',
                top:50,
                width: '800px',
                height: '400px',
                closed: false,
                cache: false,
                modal: true,
                buttons:[{
				        text:'关闭',
				        handler:function(){$('#ErrorDg').dialog('close');}
			        }]
                });
               $("#ErrorTable").datagrid({
                data:data,
                columns:[[
                      { field: 'productname', title: '件号',width:'100px' },
                      { field: 'Error', title: '出错原因',width:'400px' }
                  ]]
               });
    },
    InitWorkFlowCopyCom:function(productName)
    {
        var formData = {
            action: "GetWorkflowSelect", 
            productName: productName, 
            workflowName: "", isThisFactory:false
        };
        $.postAjax({
            url: getRootPath() + "/Ashx/CommonHandler.ashx",
            data: formData,
            ajaxSuccess: function (res) {
                if (res.Result) {
                   $('#workflowCopy').combobox({
                    data: res.DBTable,
                    valueField: 'WORKFLOWID',
                    textField: 'WORKFLOWNAME'
                   })
                } else {
                    displayMessage(res.Message, res.Result);
                }
            }
        });
    },
    //工艺版本工时复制
    WorkFlowCopy:function(){
        var copyID=$('#workflowCopy').combobox('getValue');
        var workflowId = $("#workflowContent").workflowCombo("getValue");
        var productName= $("#productContent").productCombo('getText');
         if (isNullOrWhiteSpaceStr(copyID)) {
                displayMessage("没有选择目标工艺版本", false);
                return;
            }
        var param = {
            action: "WorkFlowCopy",
            copyID: copyID,
            workflowId:workflowId,
            productName:productName
        };
        page.post(param, function (res) {
            if (res.Result) {
                page.search(workflowId);
            }
            displayMessage(res.Message, res.Result);
        });
    },
    post: function (param, callback) {
        $.ajax({
            type: "Post",
            url: page.mainUrl,
            data: param,
            cashe: false,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    }
};
    page.init();

